package cn.wolfcode.redis.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.EmployeeRole;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.RolePermission;
import cn.wolfcode.enums.RedisKey;
import cn.wolfcode.redis.service.IEmployeeRedisService;
import cn.wolfcode.service.IEmployeeRoleService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRolePermissionService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static cn.wolfcode.enums.RedisKey.EMPLOYEE_PERMISSION;


@Service
public class EmployeeRedisServiceImpl implements IEmployeeRedisService {
    @Autowired
    private StringRedisTemplate template;
    @Autowired
    private IEmployeeRoleService employeeRoleService;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private IPermissionService permissionService;
    @Override
    public void saveEmployeePermission(Employee employee) {
        //获取key值
        String key = EMPLOYEE_PERMISSION.getKey(employee.getName());
        //获取员工所有的角色
        QueryWrapper<EmployeeRole> wrapper = new QueryWrapper<>();
        wrapper.eq(employee != null,"employee_id",employee.getId());
        List<EmployeeRole> employeeRoles = employeeRoleService.list(wrapper);
        List<RolePermission> rolePermissions = new ArrayList<>();
        for (EmployeeRole employeeRole : employeeRoles) {
            QueryWrapper<RolePermission> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("role_id",employeeRole.getRoleId());
            List<RolePermission> list = rolePermissionService.list(wrapper1);
            rolePermissions.addAll(list);
            wrapper1.clear();
        }
        List<Permission> permissions = new ArrayList<>();
        for (RolePermission rolePermission : rolePermissions) {
            Permission permission = permissionService.getById(rolePermission.getPermissionId());
            permissions.add(permission);
        }
        template.opsForValue().set(key, JSON.toJSONString(permissions),EMPLOYEE_PERMISSION.getTime());
    }

    @Override
    public List<Permission> getPermission(String token) {
        String values = template.opsForValue().get(token);
        List<Permission> permissions = new ArrayList<>();
        if (StringUtils.hasLength(values)){
            permissions = JSON.parseArray(values, Permission.class);
        }
        return permissions;
    }
}
